package com.sikaryofficial.system.controller;

import cn.hutool.core.text.CharSequenceUtil;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.utils.DateUtils;
import com.sikaryofficial.common.core.utils.StringUtils;
import com.sikaryofficial.common.core.utils.poi.ExcelUtil;
import com.sikaryofficial.common.core.web.controller.BaseController;
import com.sikaryofficial.common.core.web.domain.AjaxResult;
import com.sikaryofficial.common.core.web.page.TableDataInfo;
import com.sikaryofficial.common.log.annotation.Log;
import com.sikaryofficial.common.log.enums.BusinessType;
import com.sikaryofficial.common.security.annotation.InnerAuth;
import com.sikaryofficial.common.security.annotation.RequiresPermissions;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.RemoteWorkBenchService;
import com.sikaryofficial.system.api.domain.SysDept;
import com.sikaryofficial.system.api.domain.SysRole;
import com.sikaryofficial.system.api.domain.SysUser;
import com.sikaryofficial.system.api.domain.UserReq;
import com.sikaryofficial.system.api.model.LoginUser;
import com.sikaryofficial.system.api.model.SysMemberUser;
import com.sikaryofficial.system.api.model.SysUserExtReq;
import com.sikaryofficial.system.config.HiSMKAuthConfig;
import com.sikaryofficial.system.domain.GadmCountryGeo;
import com.sikaryofficial.system.manager.UserAgeCacheManager;
import com.sikaryofficial.system.service.IGadmCountryGeoService;
import com.sikaryofficial.system.service.ISysConfigService;
import com.sikaryofficial.system.service.ISysDeptService;
import com.sikaryofficial.system.service.ISysPermissionService;
import com.sikaryofficial.system.service.ISysPostService;
import com.sikaryofficial.system.service.ISysRoleService;
import com.sikaryofficial.system.service.ISysUserOauthService;
import com.sikaryofficial.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author qinjinyuan
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private ISysPermissionService permissionService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IGadmCountryGeoService countryGeoService;
    @Resource
    private HiSMKAuthConfig authConfig;

    @Autowired
    private UserAgeCacheManager userAgeCacheManager;
    @Value("${hismk.user.defaultBirthDate}")
    private String defaultBirthDate;
    @Resource
    private ISysUserOauthService userOauthService;

    /**
     * 获取用户缓存数据
     */
    @ApiOperation(value = "获取用户缓存数据")
    @GetMapping("/userCache/{userId}")
    public R<SysUser> getSysUserInfoCacheById( @PathVariable("userId") Long userId) {
        return R.ok(userAgeCacheManager.getSysUserInfoCacheById(userId));
    }

    @Autowired
    private RemoteWorkBenchService remoteWorkBenchService;
    /**
     * 定制更新接口 (客户是否认证 & 框架合同期限)
     */
    @ApiOperation(value = "定制更新接口[客户是否认证&框架合同期限]")
    @PostMapping("/updateSysUserExtInfo")
    public R<Boolean> updateSysUserExtInfo(@Validated @RequestBody SysUserExtReq sysUserExtReq) {
        Boolean result = userService.updateSysUserExtInfo(sysUserExtReq);
        // TODO:  处理相关缓存数据 & 后续价格相关判定
        // 更新[客户是否认证&框架合同期限]
        userAgeCacheManager.updateCustomerCache(sysUserExtReq);
        // 清除商品相关缓存
        remoteWorkBenchService.removeGoodsCache();
        return R.ok(result);
    }
    /**
     * 生成随机字符串
     *
     * @param length
     * @return
     */
    public static String generateRandomString(int length) {
        String characters = "abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder result = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            result.append(characters.charAt(index));
        }
        return result.toString();
    }

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/infoByEmail/{email}")
    public R<String> infoByEmail(@PathVariable("email") String email) {
        String userName = userService.selectUserNameByEmail(email);
        if (StringUtils.isNull(userName)) {
            return R.fail("email is error.");
        }
        return R.ok(userName);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/infoByUuid/{uuid}")
    public R<String> getUserNameByUuid(@PathVariable("uuid") String uuid) {
        String userName = userService.selectUserNameByUuid(uuid);
        if (StringUtils.isNull(userName)) {
            return R.fail("userName is empty.");
        }
        return R.ok(userName);
    }

    /**
     * 邮箱唯一性校验
     */
    @GetMapping("/checkEmailUnique/{email}")
    public R<Boolean> checkEmailUnique(@PathVariable("email") String email) {
        SysUser user = new SysUser();
        user.setEmail(email);
        return R.ok(userService.checkEmailUnique(user));
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/getUserByUserId/{userId}")
    public R<SysUser> getUserByUserId(@PathVariable("userId") Long userId) {
        SysUser sysUser = userService.selectUserById(userId);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("email is error.");
        }
        return R.ok(sysUser);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        R<Boolean> fail = checkRegisterData(sysUser);
        if (Objects.nonNull(fail)) {
            return fail;
        }
        return R.ok(doUserRegister(sysUser));
    }

    @InnerAuth
    @PostMapping("/registerByH5")
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> registerByH5(@RequestBody UserReq req) {
        R<Boolean> fail = checkRegisterData(req.getSysUser());
        if (Objects.nonNull(fail)) {
            return fail;
        }
        doUserRegister(req.getSysUser());
        // 设置userId
        if(Objects.nonNull(req.getSysUserOauth())){
            req.getSysUserOauth().setUserId(req.getSysUser().getUserId());
        }
        return R.ok(userOauthService.insertSysUserOauth(req.getSysUserOauth()) > 0);
    }

    /**
     * 渠道商注册用户信息 并初始化默认角色和岗位
     */
    @InnerAuth
    @PostMapping("/registerForChannel")
    public R<Long> registerForChannel(@RequestBody SysUser sysUser) {
        R<Boolean> fail = checkRegisterData(sysUser);
        if (Objects.nonNull(fail)) {
            return R.ok(0L);
        }
        // 进行注册
        doUserRegister(sysUser);
        // 初始化默认角色和岗位
        userService.updateUser(sysUser);
        return R.ok(sysUser.getUserId());
    }

    private boolean doUserRegister(SysUser sysUser) {
        // 注册用户-获取国家信息
        if (CharSequenceUtil.isNotBlank(sysUser.getIsoCountryCode()) && CharSequenceUtil.isBlank(sysUser.getCountry())) {
            GadmCountryGeo countryGeo = countryGeoService.findCountry(sysUser.getIsoCountryCode());
            sysUser.setCountry(Objects.nonNull(countryGeo) ? countryGeo.getCountry() : null);
        }
        // 注册
        boolean flag = userService.registerUser(sysUser);
        // 更新年龄缓存
        userAgeCacheManager.updateUserAgeCache(sysUser);
        // initUserCache
        userAgeCacheManager.initUserCache(sysUser.getUserId(), sysUser);
        return flag;
    }

    private R<Boolean> checkRegisterData(SysUser sysUser) {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("The current system is disable for the registration function.");
        }
        if (userService.checkEmailUnique(sysUser)) {
            return R.fail("register email exist.");
        }
        if (userService.checkUserNameUnique(sysUser)) {
            return R.fail("register account exist.");
        }
        if (userService.nickNameCount(sysUser.getUserId(), sysUser.getNickName()) > 0) {
            return R.fail("register nick name exist.");
        }
        return null;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfoByh5")
    public R<SysUser> getInfoByh5() {
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        if (Objects.nonNull(user)) {
            user.setPassword(null);
            user.setRoles(Lists.newArrayList());
            user.setDept(null);
        }
        return R.ok(user);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 新增出生日期字段
        user.setBirthDate(DateUtils.parseDate(defaultBirthDate));
        logger.info("defaultBirthDate1:" + defaultBirthDate);
        logger.info("defaultBirthDate2:" + user.getBirthDate());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增用户
     */
    @Log(title = "新增会员", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增会员")
    @PostMapping("/addMember")
    public AjaxResult addMember(@Validated @RequestBody SysMemberUser req) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(req, user);
        if (!StringUtils.isEmailValid(user.getEmail())) {
            return error("新增会员用户失败，email is invalid");
        }
        if (userService.checkUserNameUnique(user)) {
            return error("新增会员用户'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && userService.checkPhoneUnique(user)) {
            return error("新增会员用户失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && userService.checkEmailUnique(user)) {
            return error("新增会员用户失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        String initPassword = configService.selectConfigByKey("sys.user.initPassword");
        if (CharSequenceUtil.isBlank(initPassword)) {
            throw new ServiceException("请先配置初始化密码");
        }
        initMemberData(req, user, initPassword);
        return toAjax(userService.insertUser(user));
    }

    /**
     * 初始化会员数据
     *
     * @param req
     * @param user
     * @param initPassword
     */
    private void initMemberData(SysMemberUser req, SysUser user, String initPassword) {
        // 设置默认密码
        user.setPassword(SecurityUtils.encryptPassword(initPassword));
        // 会员设置 部门 岗位
        user.setDeptId(authConfig.getDefaultDeptId());
        user.setRoleIds(new Long[]{authConfig.getDefaultRoleId()});
        user.setPostIds(new Long[]{authConfig.getDefaultPostId()});
        if (Objects.isNull(req.getAge())) {
            throw new ServiceException("age cannot be empty");
        }
        user.setBirthDate(DateUtils.getBirthDateByAge(req.getAge()));

        // 设置username
        String email = user.getEmail();
        String userName = email.substring(0, email.indexOf("@")) + generateRandomString(4);
        user.setUserName(userName);
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 初始化H5用户角色和岗位
     */
    @Log(title = "初始化用户角色和岗位", businessType = BusinessType.UPDATE)
    @PutMapping("/initH5UserRoleAndPost")
    public AjaxResult initH5UserRoleAndPost(@RequestBody SysUser user) {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 注销-停用-用户-H5
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteUserByOwner/{userIds}")
    public R<Integer> deleteUserByOwner(@PathVariable Long[] userIds) {
        return R.ok(userService.deleteUserByOwner(userIds));
    }

    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteMemberUsers/{userIds}")
    public R<Integer> deleteMemberUsers(@PathVariable Long[] userIds) {
        return R.ok(userService.deleteMemberUsers(userIds));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    @GetMapping("/selectNoticeUserList")
    @ApiOperation("获取通知用户列表")
    public R<List<SysUser>> selectNoticeUserList() {
        return R.ok(userService.selectNoticeUserList());
    }
}
